package com.sun.async.controller;

import com.sun.async.entity.ImportTask;
import com.sun.async.entity.dto.StudentImportDTO;
import com.sun.async.service.AsyncExcelImportService;
import com.sun.async.service.FileStorageService;
import com.sun.async.service.ImportTaskService;
import com.sun.async.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;
import java.nio.file.Files;

/**
 * 导入任务控制器
 */
@RestController
@RequestMapping("/api/import/task")
public class ImportTaskController {

    @Autowired
    private ImportTaskService importTaskService;

    @Autowired
    private AsyncExcelImportService asyncExcelImportService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传Excel并创建导入任务
     */
    @PostMapping("/upload")
    public String uploadExcel(@RequestParam("file") MultipartFile file,
                              @RequestParam("taskName") String taskName) {
        try {
            // 1. 手动保存上传的文件到临时目录
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            File tempFile = new File(fileStorageService.getUploadPath(), fileName);

            // 使用Files.copy确保文件被正确保存
            Files.copy(file.getInputStream(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            // 2. 创建导入任务，关联保存后的文件
            Long taskId = importTaskService.createImportTask(tempFile, taskName);

            // 3. 异步处理Excel导入，传递保存后的文件路径
            asyncExcelImportService.asyncImportExcel(taskId, tempFile, studentService);

            return "任务已创建，任务ID: " + taskId;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败: " + e.getMessage();
        }
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/{taskId}")
    public ImportTask getTaskDetail(@PathVariable Long taskId) {
        return importTaskService.getTaskDetail(taskId);
    }

    /**
     * 获取所有任务列表
     */
    @GetMapping("/list")
    public List<ImportTask> listAllTasks() {
        return importTaskService.listAllTasks();
    }

    /**
     * 下载错误文件
     */
    @GetMapping("/downloadErrorFile/{taskId}")
    public void downloadErrorFile(@PathVariable Long taskId, HttpServletResponse response) throws IOException {
        importTaskService.downloadErrorFile(taskId, response);
    }
}